﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.IO;
using System.Data;
using System.Data.SqlClient;
using System.Web.UI.HtmlControls;
using KC.DataAccess.Global;
using KC.DataAccess.MV;
using Logger = KC.Logging.Logger;
using KC.ExtensionMethods;

public partial class site : System.Web.UI.MasterPage
{
	private static string cs = System.Configuration.ConfigurationManager.ConnectionStrings["MV8"].ConnectionString;
	private DateTime started;
	
	protected void Page_Load(object sender, EventArgs e)
	{
		// Display a random header image
		{	string[] headers = Directory.GetFiles(MapPath("headers"));
			string header = headers[new Random().Next(0, headers.Length)];
			iHeader.ImageUrl = "headers/" + header.Substring(header.LastIndexOf('\\') + 1);
			headers = null;
			header = null; }

		// Display Totally Random Word
		{	string word = ((string)Global.CallSql_Query(cs, "select top 1 word from articleulator..words where len(word) < 13 and word like '%[A-Za-z]%' order by newid()").Rows[0][0]).Trim();
			if (word.Contains(' ')) word = word.Substring(0, word.IndexOf(' '));
			lblWord.Text = Server.HtmlEncode(word);
			word = null; }

		// Display Totally Random Search Query
		lblQuery.Text = Server.HtmlEncode(((string)Global.CallSql_Query(cs, "select top 1 query from searchresults where len(query) < 35 order by newid()").Rows[0][0]).Trim());

		// Display top static AdSense ad
		lblAdsense.Text = GetGoogleAdMarkup();

		// Log activity
		int PID = -1;
		if (Request.QueryString["ID"] != null) int.TryParse(Request.QueryString["ID"], out PID);
		else if (Request.QueryString["Title"] != null) {
			DataTable dtPosts = KC.DataAccess.Global.Global.CallSql_Query(cs, "select id from posts where friendlyname='" + Request.QueryString["Title"].Replace("'", "''") + "'");
			if (dtPosts != null && dtPosts.Rows.Count > 0) PID = (int)dtPosts.Rows[0][0]; }

		LogActivity(PID == -1 ? null : (int?) PID);
		LogSearchResult();

	}
	protected void Page_Init(object sender, EventArgs e)
	{
		try {
			started = DateTime.Now;
			DetectIp();
			if (session == null) InitSession(); }
		catch { }
	}
	protected void Page_PreRender(object sender, EventArgs e) { lblTime.Text = ((DateTime.Now - started).TotalHours * 40).ToString("$#0.00###");
		
	}
	private MV8DataContext dc = new MV8DataContext(cs);
	public IP ip;
	public Session session;
	private Activity act;

	public static string GetGoogleAdMarkup()
	{
		return
			"<div style=\"width: 100%; text-align:center;\">\r\n" +
			"<script type=\"text/javascript\"><!--\r\n" +
			"google_ad_client = \"ca-pub-6557158343810013\";\r\n" +
			"/* Leaderboard - kconnolly.net */\r\n" +
			"google_ad_slot = \"1090694274\";\r\n" +
			"google_ad_width = 728;\r\n" +
			"google_ad_height = 90;\r\n" +
			"//-->\r\n" +
			"</script>\r\n" +
			"<script type=\"text/javascript\" src=\"http://pagead2.googlesyndication.com/pagead/show_ads.js\"></script><br />\r\n</div>\r\n";
	}

	private void DetectIp()
	{
		// Find any IP(s) matching this address
		var ips = from a in dc.IPs
				  where a.Address == Request.UserHostAddress
				  orderby a.LastAccess descending
				  select a;
		if (ips.Count() == 1) // Exactly one match; use it.
			ip = ips.First();
		else if (ips.Count() > 1) { // Multiple matches; error out and use the most recent one.
			ip = ips.First();
			return; }
		if (ips.Count() == 0) { // No matches; add a new one
			ip = new IP();
			ip.Address = Request.UserHostAddress;
			try { ip.Domain = Request.UserHostName; }
			catch { }
			ip.FirstAccess = DateTime.Now;
			ip.Hits = 0;
			ip.isSpider = KC.Business.Net.Tracking.Spiders.isSpider(Request.UserAgent, Request.UserHostAddress);
			dc.IPs.InsertOnSubmit(ip); }

		// Update IP
		ip.Hits++;
		ip.LastAccess = DateTime.Now;
		dc.SubmitChanges();

	}
	private void InitSession()
	{
		session = new Session();
		session.dStarted = DateTime.Now;
		session.dEnded = DateTime.Now;
		session.IPID = ip.ID;
		session.UID = null;
		dc.Sessions.InsertOnSubmit(session);
		dc.SubmitChanges();
	}
	public void LogActivity(int? PostID)
	{
		try {
			act = new Activity();
			act.SID = session.ID;
			act.DateTime = DateTime.Now;
			if (PostID != null) act.PID = PostID;
			act.Request = Request.Url.AbsoluteUri;
			act.Referrer = Request.UrlReferrer == null ? null : Request.UrlReferrer.AbsoluteUri;
			act.UserAgent = Request.UserAgent;
			dc.Activities.InsertOnSubmit(act);
			dc.SubmitChanges(); }
		catch (Exception ex) {
			if (!Request.Url.AbsoluteUri.ToLower().Contains("sitemap.aspx"))
				Response.Write(ex.ToString());
			Logger.LogError(Logger.Project.MV, Logger.ErrorLevel.Error, ex.Message); }

		// Known, positive, Russian referral spam scheme.  Possible botnet or IP & UA spoofing.
		if (Request.UrlReferrer != null && Request.UrlReferrer.AbsoluteUri != null && Request.UrlReferrer.AbsoluteUri.ToLower().Contains("sitemap") && Request.UrlReferrer.AbsoluteUri.ToLower().EndsWith(".html") && !Request.Url.AbsoluteUri.ToLower().Contains("accessdenied.aspx")) {
			Response.StatusCode = 403;
			Response.Status = "403 Forbidden";
			Response.AddHeader("Warning", "I know what you're doing, and I'm watching you.");
			ip.NumProblems++;
			dc.SubmitChanges();
			Response.Redirect("AccessDenied.aspx"); }


		if (!ip.isSpider && !Request.Url.AbsoluteUri.ToLower().Contains("sitemap.aspx") && !Request.Url.AbsoluteUri.ToLower().Contains("accessdenied.aspx"))
		{
			if (ip.NumProblems > 0)
				Response.Redirect("AccessDenied.aspx");
			try {
				if ((int)KC.DataAccess.Global.Global.CallSql_Query(cs, "select count(id) from blacklist where len(domain)>3 and '" + Request.UrlReferrer.Host.Replace("'", "''") + "' like '%'+domain+'%'").Rows[0][0] > 0)
					Response.Redirect("AccessDenied.aspx"); }
			catch { } }

	}
	private void LogSearchResult()
	{
		// Detect whether this is a search engine referrer
		//if (Request.UrlReferrer == null || string.IsNullOrEmpty(Request.UrlReferrer.AbsoluteUri)) return;
		string
			engine = null,
			query = null;
		//Response.Write("Search result <br />");
		if (!KC.Business.Web.RequestTools.isSearchEngineReferral(Request.UrlReferrer, out engine, out query)) return;
		//Response.Write("2");

		SearchResult sr = new SearchResult();
		sr.Query = query;
		sr.Engine = engine;
		sr.FullURL = Request.UrlReferrer.AbsoluteUri;
		sr.BaseURL = Request.UrlReferrer.GetRootDomain();
		sr.datetime = DateTime.Now;
		sr.AID = act.ID;
		dc.SearchResults.InsertOnSubmit(sr);
		dc.SubmitChanges();
		//Response.Write("3");
	}

	public static string GetFacebookCommentsScript(string url) { return "<div class=\"fb-comments\" data-href=\"" + url + "\" data-num-posts=\"4\" data-width=\"900\"></div>"; }
	public static string GetFacebookLikeButton(string url) { return "<div class=\"fb-like\" data-href=\"" + url + "\" data-send=\"true\" data-width=\"450\" data-show-faces=\"true\" data-font=\"arial\"></div>"; }

}
